package com.example.filter;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.Utils.jwtUtils;
import com.example.pojo.Result;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//import jakarta.servlet.http.HttpServletRequest;
//import jakarta.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import java.util.Enumeration;

@Component
@Slf4j
public class LoginHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 强制设置请求和响应的字符编码为UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");


        if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
            return true;
        }
        //1.获取请求url
        String url = request.getRequestURI().toString();
        //2.获取请求头中的令牌（token）
        String jwt = request.getHeader("u_token");
        //2.1判断，如果jwt令牌为空，返回未登录信息
        if (jwt==null){
            Result error = Result.error(401,"NOT_LOGIN");
            //手动转换，对象为Josn格式
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }
        //2.2判断令牌
        jwt = jwt.replace("\"","");
        //4.判断令牌是否存在，如果不存在，返回错误结果（未登录）。
        if(!StringUtils.hasLength(jwt)){
            Result error = Result.error(401,"NOT_LOGIN");
            //手动转换，对象为Josn格式
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }
        //5.解析token，如果解析失败，返回错误结果（未登录）
        try {
            jwtUtils.parseJWT(jwt);
        } catch (Exception e){//jwt解析失败
            e.printStackTrace();
            Result error = Result.error(401,"NOT_LOGIN");
            //手动转换，对象为Josn格式
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }
        //6.放行。
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

}